#ifndef __RING_BUFFER_H__
#define __RING_BUFFER_H__

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>

typedef unsigned char   uint8;
typedef unsigned short  uint16;
typedef unsigned int    uint32;

 #define min(x,y) ({ \
     typeof(x) _x = (x); \
     typeof(y) _y = (y); \
     (void)(&_x == &_y); \
     _x < _y ? _x : _y;})

struct ring_buffer {
    char *buffer;
    uint32 size;
    uint32 in;
    uint32 out;
    pthread_mutex_t mutex;
    sem_t sem;
};

static inline void ring_buffer_reset(struct ring_buffer *p_ring_buffer)
{
    p_ring_buffer->in = p_ring_buffer->out = 0;
}

static inline uint32 ring_buffer_len(struct ring_buffer *p_ring_buffer)
{
    return p_ring_buffer->in - p_ring_buffer->out;
}


extern struct ring_buffer *ring_buffer_alloc(uint32 size);
extern void ring_buffer_free(struct ring_buffer *p_ring_buffer); 
extern uint32 ring_buffer_put(struct ring_buffer *p_ring_buffer, char *buffer, uint32 len);
extern uint32 ring_buffer_get(struct ring_buffer *p_ring_buffer, char *buffer, uint32 len);

#endif